<?php
defined('BASEPATH') or exit('No direct script access allowed');

class PermissionManage extends MY_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model('Permission');
    }

    /* 默认方法 */
    public function index()
    {}

    /* 显示权限树 */
    public function showPermission()
    {
        $result = $this->Permission->find();
        $tree = $this->getChild(0, $result);
        $data = $this->getTreeOfJson($tree);
        echo json_encode($data);
    }

    /* 获取子节点 */
    private function getChild($pid, $data)
    {
        $tree = array();
        foreach ($data as $k => $v) {
            if ($v['pid'] == $pid) {
                unset($data[$k]);
                $tmp['id'] = $v['id'];
                $tmp['pid'] = $v['pid'];
                $tmp['name'] = $v['name'];
                $tmp['child'] = $this->getChild($v['id'], $data);
                $tree[] = $tmp;
            }
        }
        return $tree;
    }

    /* 将分类树数组转变成json数组 */
    private function getTreeOfJson($tree)
    {
        $data = array();
        foreach ($tree as $k => $v) {
            $tmp['id'] = $v['id'];
            $tmp['parentId'] = $v['pid'];
            $tmp['name'] = $v['name'];
            $data[] = $tmp;
            if ($v['child']) {
                $child = $this->getTreeOfJson($v['child']);
                foreach ($child as $k2=>$v2){
                    $data[]=$v2;
                }
            }
        }
        return $data;
    }
}
